package com.orangelife.mobile.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.jump.LocationJumper;
import com.common.sp.CommSp2;
import com.common.sp.OtherSp;
import com.common.sp.UserSp;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.CountDownHandler;
import com.curry.android.util.StringUtil;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.common.jump.HouseJumper;
import com.orangelife.mobile.common.view.ConfirmDialog;

import com.orangelife.mobile.main.biz.JumpUtil;
import com.orangelife.mobile.main.biz.MainHttpBz;
import com.orangelife.mobile.main.view.RedEnvelopeActivity;
import com.orangelife.mobile.myhouse.biz.HouseHttpBiz;

import com.orangelife.mobile.util.LogE;
import com.sdu.didi.openapi.DiDiWebActivity;


import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 首页
 * <p/>
 * Create by cx.Modify by wgf on 160714.
 *
 * @author chenxiang
 * @since v3.0
 */
public class Page1Fragment extends OrangeLifeBaseFragment {

    private View homePageView;

    @Bind(R.id.tvHomeTitle)
    TextView tvTitle;
    @Bind(R.id.llHomeTitle)
    LinearLayout llHomeTitle;
    @Bind(R.id.ib_phone)
    ImageButton ibPhone;
    @Bind(R.id.tv_versionType)
    TextView tVversionType;
    @Bind(R.id.tvEnvelope)
    TextView tvEnvelope;
    @Bind(R.id.ib_switch)
    ImageView ibSwitch;

    /**
     * 广告轮播Fragment
     */
    BannerFragment bannerFragment;
    /**
     * 文字公告Fragment
     */
    RollAdsFragment rollAdsFragment;
    /**
     * 第一层服务Fragment
     */
    Fragment1 fragment1;
    /**
     * 第二层服务Fragment
     */
    Servicefragment servicefragment;
    private int isOneStrat = 0;

    /** Activit 名称 **/
    final String MODULE_NAME = "/houseKpr";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (CurryApplication.getInstance().isUpdate() && Constant.FIRST_OPEN.equals("0")) {
//            Constant.FIRST_OPEN = "1";
//            bindService();
//        }

        DataTrack.identify();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        isDestroyView = false;
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.activity_home_page,
                    container, false);
            ButterKnife.bind(this, homePageView);
            isConnected();
            initInnerFragment();
            intiDiDi();
            // initAdvert();
            ButterKnife.bind(this, homePageView);
            findView();
        } else {
            ButterKnife.bind(this, homePageView);
        }
        clearChildView(homePageView);
        return homePageView;
    }

    /**
     * 数据采集体不要删除
     *
     * @return
     */
    public Map<String, Object> getDataTrack() {
        Map<String, Object> map = new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        return map;
    }

    @Override
    public void onResume() {
        super.onResume();
        isConnected();
        /*应该在每次切换小区的时候请求*/
        requestCustomerServicePhone();
        /*每次亮屏的时候，请求红包倒计时秒数*/
        requestNextRedEnvelopeTime();
        requestHasCert();
        if (isOneStrat == 1) {
            requestFeatures1();
            requestFeatures2();
            requestAdList();
            requestAnnouncementList();
        }
        isOneStrat = 1;

    }

    private void requestHasCert() {
        /*如果保存的LoginID和现在的LoginID不同，说明已经切换了，需要重新获取，如果认证名为空，也要一直获取*/
        if (!UserSp.getLoginID().equals(OtherSp.getLastLoginID()) || StringUtil.isBlank(UserSp.getCertName())) {
            HouseHttpBiz.getHasCert();
        }
        /*如果已经切换了小区或者当前小区还未认证，需要一直请求*/
        if (!CommSp2.getCommID().equals(OtherSp.getLastCommID()) || !UserSp.hasCertInCurrentComm()) {
            HouseHttpBiz.getHasCertInCurrentComm();
        }
    }


    private void intiDiDi() {
        DiDiWebActivity.registerApp("didi4A58574D6248643467577973547349", "46656fe18d30ce04aa0836a31314dc73");
    }


    private void initInnerFragment() {
        rollAdsFragment = new RollAdsFragment();//文字公告
        servicefragment = new Servicefragment();//服务
        fragment1 = new Fragment1();//服务
        bannerFragment = new BannerFragment();//广告轮播
        //向活动添加碎片,根据屏幕的纵向和横向显示
        //1,获取碎片管理器
        FragmentManager fragment = getFragmentManager();
        //2,碎片的显示需要使用FragmentTransaction类操作
        FragmentTransaction transacction = fragment.beginTransaction();
        transacction.replace(R.id.fragment1, rollAdsFragment);
        transacction.replace(R.id.fragment2, fragment1);
        transacction.replace(R.id.fragment3, servicefragment);
        transacction.replace(R.id.fl_banner, bannerFragment);
        transacction.commit();
    }

    /**
     * 绑定对象或者赋值
     */
    private void findView() {
        tvTitle.setText(CommSp2.getCommName());
        //版本标记
        tVversionType.setText(getResources().getString(R.string.server_name));
    }

    /**
     * 请求走马灯公告列表
     */
    private void requestAnnouncementList() {
        if (rollAdsFragment != null) {
            rollAdsFragment.requestAllAds();
        }
    }

    private void requestFeatures1() {
        if (fragment1 != null) {
            fragment1.requestFeatures();
        }
    }

    private void requestFeatures2() {
        if (servicefragment != null) {
            servicefragment.requestFeatures();
        }
    }

    /**
     * 请求轮播广告列表
     */
    private void requestAdList() {
        if (bannerFragment != null) {
            bannerFragment.requestAdList();
        }
    }

//    /** 请求版本更新 */
//    private void requestUpdateVersion() {
//        new UpdateManager(getActivity(), false);
//    }


    /**
     * 请求物业电话
     */
    private void requestCustomerServicePhone() {
        if (TextUtils.isEmpty(CommSp2.getCustomerServicePhone())) {/*如果物业电话为空，则重新请求*/
            MainHttpBz.getCustomerServicePhone();
        }
    }

    @OnClick({R.id.llHomeTitle, R.id.ib_phone, R.id.tvEnvelope})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llHomeTitle://切换小区
                dataTrackClick("selCagComm", null);
                LocationJumper.jumpToSelectCity(getActivity());
                break;
            case R.id.ib_phone:
                OrangePhoneUtil.callCommProperty(getActivity());
                // FIXME: 16/11/25 测试用，提交的时候一定要注释掉
//                JumpUtil.jumpActivity(getActivity(), "");
                dataTrackClick("btnCallEstateServ", null);
                break;
            case R.id.tvEnvelope:
                showRedEnvelope();
                stopHeartBeat();
                break;
        }
    }


    /**
     * 打开红包界面
     */
    private void showRedEnvelope() {
        Intent intent = new Intent(getActivity(), RedEnvelopeActivity.class);
        intent.putExtra("isCountDown", isCountDown);
        startActivityForResult(intent, 0);
        tvEnvelope.setClickable(false);
    }

    private boolean isCountDown = false;

    //红包界面点击打开，肯定要回调方法回来，告诉这个界面，红包已经拆开了；CALLBACK
    boolean hasOpenLastEnvelope = true;

    private void requestNextRedEnvelopeTime() {
        if (!hasOpenLastEnvelope) {//如果上次开奖的时候，红包没拆开，则不显示倒计时
            if (coundDownHandler != null && isCountDown) {
                coundDownHandler.stopTimer();
                isCountDown = false;
            }
            tvEnvelope.setVisibility(View.VISIBLE);
            tvEnvelope.setText("抢红包");
        } else {
            MainHttpBz.getNextRedEnvelopeTime(new VolleyHttpUtil.ResponseCallBack() {
                @Override
                public void handleResponse(JSONObject response, int errCode) {
                    if (isDestroyView) {
                        return;
                    }
                    nextRedEnvelopeTime = "-1";
                    if (OrangeErrorHandler.getInstance().isSuccess(response, false)) {
                        ArrayList<String> list = OrangeDataHandler.getValueListWithEntity(response, "nextTime");
                        if (list != null && list.size() == 1) {
                            nextRedEnvelopeTime = list.get(0);
                        }
                    }
                    startTimer();
                }
            });
        }
    }

    private void playHeartbeatAnimation() {
        LogE.E("开始动画");
        AnimationSet swellAnimationSet = new AnimationSet(true);
        swellAnimationSet.addAnimation(new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f));
        swellAnimationSet.addAnimation(new AlphaAnimation(1.0f, 0.3f));

        swellAnimationSet.setDuration(500);
        swellAnimationSet.setInterpolator(new AccelerateInterpolator());
        swellAnimationSet.setFillAfter(true);

        swellAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                AnimationSet shrinkAnimationSet = new AnimationSet(true);
                shrinkAnimationSet.addAnimation(new ScaleAnimation(1.2f, 1.0f, 1.2f, 1.0f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f));
                shrinkAnimationSet.addAnimation(new AlphaAnimation(0.3f, 1.0f));
                shrinkAnimationSet.setDuration(1000);
                shrinkAnimationSet.setInterpolator(new DecelerateInterpolator());
                shrinkAnimationSet.setFillAfter(false);
                if (tvEnvelope != null) {
                    tvEnvelope.clearAnimation();
                    tvEnvelope.startAnimation(shrinkAnimationSet);// 动画结束时重新开始，实现心跳的View
                }
            }
        });
        if (tvEnvelope != null) {
            tvEnvelope.clearAnimation();
            tvEnvelope.startAnimation(swellAnimationSet);
        }
    }


    private boolean isStopAnimation;

    private class HeatbeatThread extends Thread {
        public void run() {
            LogE.E("HeatbeatThread run");
            try {
                sleep(100);
                while (!isStopAnimation) {
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(new Runnable() {
                            public void run() {
                                LogE.E("runOnUiThread run");
                                if (!isStopAnimation) {
                                    playHeartbeatAnimation();
                                }
                            }
                        });
                    }
                    Thread.sleep(1500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private Thread heartbeatThread;

    /**
     * 开始心跳
     */
    private void startHeartBeat() {
        isStopAnimation = false;
        if (heartbeatThread == null) {
            heartbeatThread = new HeatbeatThread();
        }
        if (!heartbeatThread.isAlive()) {
            heartbeatThread.start();
        }
    }

    /**
     * 停止心跳
     */
    private void stopHeartBeat() {
        isStopAnimation = true;
        if (heartbeatThread != null && !heartbeatThread.isInterrupted()) {
            heartbeatThread.interrupt();
            heartbeatThread = null;
            System.gc();
        }
        if (tvEnvelope != null) {
            tvEnvelope.clearAnimation();
        }
    }


    private void startTimer() {
        if ("-1".equals(nextRedEnvelopeTime)) {  //如果返回的秒数=-1，表示没有抢红包活动，隐藏红包按钮
//            tvEnvelope.setText("红包活动结束了");
            tvEnvelope.setVisibility(View.GONE);
        } else {//否则表示有抢红包活动
            tvEnvelope.setVisibility(View.VISIBLE);
            tvEnvelope.setClickable(true);
            tvEnvelope.setText("抢红包");
            isCountDown = true;
            initCoundDownHandler();
        }
    }

    private void initCoundDownHandler() {
        if (coundDownHandler == null) {
            coundDownHandler = new CountDownHandler(tvEnvelope, 1);
            coundDownHandler.setOnCountDownTimerFinishedListener(new CountDownHandler.OnCountDownTimerFinishedListener() {
                @Override
                public void onFinish() {//为0的时候，倒计时结束
                    hasOpenLastEnvelope = false;
                    isCountDown = false;
                    tvEnvelope.setText("抢红包");
                    startHeartBeat();
                }

                @Override
                public void onCountDown(String currentSecond) {
                }
            });
        }
        coundDownHandler.startTimer(nextRedEnvelopeTime);
    }

    private CountDownHandler coundDownHandler;

    private String nextRedEnvelopeTime = "0";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            tvEnvelope.setClickable(true);
        /*从红包界面回来之后，要将在红包界面是否打开了红包这件事传回来*/
            hasOpenLastEnvelope = data.getBooleanExtra("hasOpenEnvelope", false);
            boolean hasCert = data.getBooleanExtra("hasCert", false);
            if (!hasCert) {
                showCertDialog();
            }
        }
    }

    private void showCertDialog() {
        //跳转到认证界面；
        final ConfirmDialog dialog1 = new ConfirmDialog(getActivity(), "提示", "本次活动需要认证后才可参与",
                "取消", "认证");
        dialog1.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog1.dismiss();
            }

            @Override
            public void doRight() {
                dialog1.dismiss();
                HouseJumper.jumpToCert(getActivity(), "false");
            }
        });
        dialog1.show();
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    boolean isDestroyView;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        isDestroyView = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopHeartBeat();
        if (coundDownHandler != null) {
            coundDownHandler.stopTimer();
        }
    }
}
